import axios, {AxiosStatic} from "axios";
import {Message} from "element-ui";
import router from "@/router";
//* 定义响应拦截器。在响应拦截器中，对请求结果进行预处理,   定义根据响应回来的相关数据进行处理,
axios.interceptors.response.use(success => {
    //业务逻辑错误,非服务器错误
    if (success.status && success.status == 200 && success.data.status == 500) {
        Message.error({message: success.data.msg})
        return;  //这样表示返回空值.这个逻辑也是走 axios的then逻辑,不是catch逻辑,所以then里的data是空的
    }
    if (success.data.msg) {
        Message.success({message: success.data.msg});
    }
    return success.data;
}, error => {
    if (error.response.status == 504 || error.response.status == 404) {
        Message.error({message: '服务器错误'})
    } else if (error.response.status == 403) {
        Message.error({message: '没有权限'})
    } else if (error.response.status == 401) {
        Message.error({message: error.response.data.msg ? error.response.data.msg : '尚未登录，请登录'})
        router.replace('/');
        // // this.$router.replace("/")

    } else {

        if (error.response.data.msg) {
            Message.error({message: error.response.data.msg})
        } else {
            Message.error({message: '未知错误!'})
        }
    }
    return
})


export const postKeyValueRequest = function (url, params) {
    //不能使用 axios.post(...)的方式写,因为这里要返回一个对象.不是条用方法.
    return axios({
        method: 'post',
        url: url,
        data: params,
        transformRequest: [function (data) {
            let ret = '';
            for (let i in data) {
                ret += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&'
            }
            return ret;
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
}

export const postRequest = (url, params) => {
    return axios({
        method: 'post',
        url: url,
        data: params
    })
}

export const putRequest = (url, params) => {
    return axios({
        method: 'put',
        url: url,
        data: params
    })
}

export const getRequest = (url, params) => {
    return axios({
        method: 'get',
        url: url,
        data: params
    })
}

export const deleteRequest = (url, params) => {
    return axios({
        method: 'delete',
        url: url,
        data: params
    })
}

